package cn.swu.ghx.swu.library.fragment

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import cn.swu.ghx.swu.library.R
import cn.swu.ghx.swu.library.data.AppDatabase
import cn.swu.ghx.swu.library.data.getDb
import cn.swu.ghx.swu.library.data.teacher.Teacher
import cn.swu.ghx.swu.library.data.teacher.TeacherIpt
import cn.swu.ghx.swu.library.databinding.DialogTeacherAddBinding
import cn.swu.ghx.swu.library.databinding.FragmentTeacherBinding
import cn.swu.ghx.swu.library.databinding.ItemTeacherBinding
import cn.swu.ghx.swu.library.model.TeacherViewModel
import com.elvishew.xlog.XLog
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import kotlin.concurrent.thread

/**
 * MVVM
 * 1. databinding
 * 2. viewmodel
 * 3. livedata
 */
class TeacherFragment : Fragment() {

    lateinit var vm: TeacherViewModel

    lateinit var db: AppDatabase

    lateinit var adapter: TeacherAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        db = getDb()
        vm = ViewModelProvider(this).get(TeacherViewModel::class.java)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        val binding = DataBindingUtil.inflate<FragmentTeacherBinding>(
            inflater,
            R.layout.fragment_teacher,
            container,
            false
        )

        binding.vm = vm

        //
        adapter = TeacherAdapter()
        binding.recycler.adapter = adapter
        // 弹框
        binding.btnAdd.setOnClickListener {
            showAddDialog()
        }

        return binding.root
    }

    fun showAddDialog() {

        // TODO
        val ipt = TeacherIpt()
        val binding =DialogTeacherAddBinding.inflate(requireActivity().layoutInflater)
        binding.item = ipt
        MaterialAlertDialogBuilder(requireActivity())
            .setView(binding.root)
            .setNegativeButton("取消") { d, w ->
                d.dismiss()
            }
            .setPositiveButton("确定") { d, w ->
                XLog.d("新增教师：name=%s,birth=%s,remark=%s,phone=%s", ipt.name, ipt.birth, ipt.remark,ipt.phone)
                saveTeacher(ipt.name,ipt.birth,ipt.remark,ipt.phone)
                d.dismiss()
            }
            .show()
    }

    private fun saveTeacher(name: String, birth: String, remark: String,phone:String) {
       thread {
           db.teacherDao().save(Teacher(name=name, birth = birth, remark = remark, telPhone = phone))
           loadData()
       }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

//        val iptSearch = view.findViewById<TextInputEditText>(R.id.ipt_search)
//
//        val txtName = view.findViewById<TextView>(R.id.txt_name)
//
//        iptSearch.addTextChangedListener {
//            txtName.text = it.toString()
//        }
        loadData()
    }

    private fun loadData() {
        thread {


            db.teacherDao().apply {
                val rows = this.all() // 所有教师
                XLog.d("查询所有教师：%s",rows.size)

                vm.rows.apply {
                    clear()
                    addAll(rows)
                }

            }
        }
    }


    inner class TeacherAdapter : RecyclerView.Adapter<TeacherViewHolder>() {


        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TeacherViewHolder {
            // databinding
            val binding = DataBindingUtil.inflate<ItemTeacherBinding>(
                LayoutInflater.from(parent.context),
                R.layout.item_teacher,
                parent,
                false
            )
            return TeacherViewHolder(binding)
        }

        override fun getItemCount() = vm.rows.size

        override fun onBindViewHolder(holder: TeacherViewHolder, position: Int) {
            holder.render(vm.rows[position])
        }

    }

    inner class TeacherViewHolder(val binding: ItemTeacherBinding) : ViewHolder(binding.root) {
        fun render(teacher: Teacher) {
            binding.item = teacher
        }

    }
}